package com.jgssp.ad.sdk.topon.adapter;

import android.app.Activity;
import android.content.Context;

import com.anythink.core.api.ATAdConst;
import com.anythink.core.api.ATBiddingListener;
import com.anythink.core.api.ATBiddingResult;
import com.anythink.core.api.MediationInitCallback;
import com.anythink.interstitial.unitgroup.api.CustomInterstitialAdapter;

import java.util.Map;
import java.util.UUID;

import cn.jiguang.jgssp.ad.ADJgInterstitialAd;
import cn.jiguang.jgssp.ad.data.ADJgInterstitialAdInfo;
import cn.jiguang.jgssp.ad.error.ADJgError;
import cn.jiguang.jgssp.ad.listener.ADJgInterstitialAdListener;

/**
 * @Description:
 * @Author: maipian
 * @CreateDate: 2021/12/7 2:58 PM
 */
public class InterstitialAdapter extends CustomInterstitialAdapter {
    private ADJgInterstitialAd interstitialAd;
    private String slotId;
    private boolean isAgreePrivacyStrategy;
    private boolean isBidding;
    private ADJgInterstitialAdInfo mInterstitialAdInfo;
    private ATBiddingListener biddingListener;

    @Override
    public void loadCustomNetworkAd(final Context context, Map<String, Object> serverExtra, Map<String, Object> localExtra) {
        if (serverExtra.containsKey("slot_id")) {
            slotId = (String) serverExtra.get("slot_id");
        }
        InitManager.getInstance().
                initSDK(context, serverExtra, isAgreePrivacyStrategy, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        startLoad(context);
                    }

                    @Override
                    public void onFail(String s) {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1001", s);
                        }
                    }
                });

    }

    @Override
    public boolean startBiddingRequest(final Context context, Map<String, Object> serverExtra, Map<String, Object> localExtra, ATBiddingListener biddingListener) {
        this.isBidding = true;
        this.biddingListener = biddingListener;
        if (serverExtra.containsKey("slot_id")) {
            slotId = (String) serverExtra.get("slot_id");
        }
        InitManager.getInstance().
                initSDK(context, serverExtra, isAgreePrivacyStrategy, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        startLoad(context);
                    }

                    @Override
                    public void onFail(String s) {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1001", s);
                        }
                    }
                });
        return true;
    }

    private void startLoad(final Context context) {
        postOnMainThread(new Runnable() {
            @Override
            public void run() {
                if (!(context instanceof Activity)) {
                    if (isBidding) {
                        if (biddingListener != null) {
                            biddingListener.onC2SBiddingResultWithCache(
                                    ATBiddingResult.fail("context is null or context must be Activity"),
                                    null);
                        }
                    } else {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1", "context is null or context must be Activity");
                        }
                    }
                    return;
                }

                interstitialAd = new ADJgInterstitialAd((Activity) context);
                interstitialAd.setListener(new ADJgInterstitialAdListener() {
                    @Override
                    public void onAdExpose(ADJgInterstitialAdInfo adJgInterstitialAdInfo) {
                        if (mImpressListener != null) {
                            mImpressListener.onInterstitialAdShow();
                        }
                    }

                    @Override
                    public void onAdClick(ADJgInterstitialAdInfo adJgInterstitialAdInfo) {
                        if (mImpressListener != null) {
                            mImpressListener.onInterstitialAdClicked();
                        }
                    }

                    @Override
                    public void onAdClose(ADJgInterstitialAdInfo adJgInterstitialAdInfo) {
                        if (mImpressListener != null) {
                            mImpressListener.onInterstitialAdClose();
                        }
                    }

                    @Override
                    public void onAdFailed(ADJgError error) {
                        if (isBidding) {
                            if (biddingListener != null) {
                                biddingListener.onC2SBiddingResultWithCache(
                                        ATBiddingResult.fail(error.getError()),
                                        null);
                            }
                        } else {
                            if (mLoadListener != null) {
                                mLoadListener.onAdLoadError("" + error.getCode(), "" + error.getError());
                            }
                        }
                    }

                    @Override
                    public void onAdReceive(ADJgInterstitialAdInfo adInfo) {
                        mInterstitialAdInfo = adInfo;
                        if (isBidding) {
                            if (biddingListener != null) {
                                if (adInfo != null && adInfo.getECPM() > 0) {
                                    //用于标识此次竞价的唯一ID，可使用UUID或者时间戳
                                    String token = UUID.randomUUID().toString();
                                    biddingListener.onC2SBiddingResultWithCache(
                                            ATBiddingResult.success(
                                                    adInfo.getECPM()
                                                    , token
                                                    , null
                                                    , ATAdConst.CURRENCY.RMB
                                            ),
                                            null
                                    );
                                } else {
                                    biddingListener.onC2SBiddingResultWithCache(
                                            ATBiddingResult.fail("adInfo is null")
                                            , null
                                    );
                                }
                            }
                        } else {
                            if (mLoadListener != null) {
                                mLoadListener.onAdCacheLoaded();
                            }
                        }
                    }

                    @Override
                    public void onAdReady(ADJgInterstitialAdInfo adJgInterstitialAdInfo) {

                    }
                });
                interstitialAd.loadAd(getNetworkPlacementId());
            }
        });


    }

    @Override
    public void show(Activity activity) {
        if (isAdReady()) {
            if (mInterstitialAdInfo != null && activity != null) {
                mInterstitialAdInfo.showInterstitial(activity);
            }
        }
    }

    @Override
    public boolean isAdReady() {
        return mInterstitialAdInfo != null;
    }

    @Override
    public String getNetworkPlacementId() {
        return slotId;
    }

    @Override
    public String getNetworkSDKVersion() {
        return InitManager.getInstance().getNetworkVersion();
    }

    @Override
    public String getNetworkName() {
        return InitManager.getInstance().getNetworkName();
    }

    @Override
    public void destory() {
        if (interstitialAd != null) {
            interstitialAd.release();
            interstitialAd = null;
        }

        if (mInterstitialAdInfo != null) {
            mInterstitialAdInfo.release();
            mInterstitialAdInfo = null;
        }

        biddingListener = null;
    }

    /**
     * @param context
     * @param isConsent   用户是否授权
     * @param isEUTraffic 是否是欧盟地区
     * @return
     */
    @Override
    public boolean setUserDataConsent(Context context, boolean isConsent, boolean isEUTraffic) {
        isAgreePrivacyStrategy = isConsent;
        return super.setUserDataConsent(context, isConsent, isEUTraffic);
    }
}
